/**
 * Copyright 北京彩通农旗资讯有限公司 All rights reserved.
 * 北京彩通农旗资讯有限公司 专有/保密源代码,未经许可禁止任何人通过任何* 渠道使用、修改源代码.
 */
package com.xspace.android.xafcommon.db.dbsub;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.xspace.android.xafcommon.been.WorkItem;
import com.xspace.android.xafcommon.db.BaseSql;
import com.xspace.android.xafcommon.util.LogUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


/**
 * 离线代办任务
 * <p/>
 * <p>Copyright: Copyright (c) 2011</p>
 * <p>公司名称 : 北京彩通农旗资讯有限公司</p>
 * <p>项目名称 : MAF-Android</p>
 * <p>创建时间 : 2016年4月22日 上午10:55:44</p>
 * <p>类描述 :         </p>
 *
 * @author <a href=" ">liuchen</a>
 * @version 1.0.0
 */
public class CacheBackLogDB extends BaseSql {
    //    private final String type = "type ";
//    private final String userid = "userid ";
//    private final String objid = "objid ";
//    private final String isselect = "isselect ";
//    private final String content = "content ";
//    private final String formid = "formid";
//    private final String InsertTime = "inserttime";
//    private final String tag = "CacheBackLogDB";
    private static final String TAG = "CacheBackLogDB";
    private MyDBHelper helpDb;
    private SQLiteDatabase sqldb;
    private String TableName = "CacheBackLog";
    private final String FormHasapply = "form_hasapply";
    private final String ObjectId = "object_id";
    private final String ObjectName = "object_name";
    private final String tableName = "table_name";
    private final String ObjectType = "object_type";
    private final String ScheduleId = "schedule_id";
    private final String ServiceobjId = "serviceobj_id";
    private final String ServiceType = "service_type";
    private final String WorkId = "work_id";
    private final String WorkTypename = "work_typename";
    private final String WorkType = "work_type";
    private final String WorkTime = "work_time";
    private final String WorkCycle = "work_cycle";
    private final String WorkTimes = "work_times";
    private final String WorkEndtime = "work_endtime";
    private final String WorkFinishtimes = "work_finishtimes";
    private final String HandlerId = "handler_id";
    private final String HandlerKey = "handler_key";
    private final String HandlerUrlview = "handler_urlview";
    //当作userId
    private final String Remark1 = "remark1";
    private final String Remark2 = "remark2";
    private final String Remark3 = "remark3";

    @Override
    public void create(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TableName
                        + " (_ID INTEGER PRIMARY KEY AUTOINCREMENT,"
                        + FormHasapply + " text,"
                        + ObjectId + "  text,"
                        + ObjectName + "  text,"
                        + ObjectType + " text,"
                        + ScheduleId + "  text,"
                        + ServiceobjId + "  text,"
                        + ServiceType + "  text,"
                        + WorkId + "  text,"
                        + WorkTypename + "  text,"
                        + WorkType + "  text,"
                        + WorkTime + "  text,"
                        + WorkCycle + "  text,"
                        + WorkTimes + "  text,"
                        + WorkEndtime + "  text,"
                        + tableName + "  text,"
                        + WorkFinishtimes + "  text,"
                        + HandlerId + "  text,"
                        + HandlerKey + "  text,"
                        + HandlerUrlview + "  text,"
                        + Remark1 + "  text,"
                        + Remark2 + "  text,"
                        + Remark3 + "  text);"
        );
    }

    public CacheBackLogDB() {

    }

    public void dropTable(SQLiteDatabase db) {
        db.execSQL("DROP TABLE IF EXISTS " + TableName);
    }

    public CacheBackLogDB(MyDBHelper db) {
        super(db);
        helpDb = db;
    }

    @Override
    public void upgrade(SQLiteDatabase arg0) {

    }

    public void closeDbAndCursor(Cursor cursor) {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
        /*
         * if (db != null) { db.close(); db = null; }
		 */
    }

    private void openDB() {
        helpDb.open();
        sqldb = helpDb.mDatabase;

    }

    private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private ContentValues buildContentValues(WorkItem item) {
        ContentValues cv = new ContentValues();
        cv.put(FormHasapply, item.form_hasapply);
        cv.put(ObjectId, item.object_id);
        cv.put(tableName, item.table_name);
        cv.put(ObjectName, item.object_name);
        cv.put(ObjectType, item.object_type);
        cv.put(ScheduleId, item.schedule_id);
        cv.put(ServiceobjId, item.serviceobj_id);
        cv.put(ServiceType, item.service_type);
        cv.put(WorkId, item.work_id);
        cv.put(WorkTypename, item.work_typename);
        cv.put(WorkType, item.work_type);
        cv.put(WorkTime, item.work_times);
        cv.put(WorkCycle, item.work_cycle);
        cv.put(WorkTimes, item.work_times);
        cv.put(WorkEndtime, item.work_endtime);
        cv.put(HandlerId, item.apply_form_id);
        cv.put(HandlerKey, item.apply_form_key);
        cv.put(HandlerUrlview, item.apply_form_url);
        cv.put(WorkFinishtimes, item.work_finishtimes);
        return cv;
    }

//    public void updateAllDataByUserId(List<WorkItem> dataList, String userId) {
//        openDB();
//        where = Remark1 + "=?";
//        selectionArgs = new String[]{userId};
//        int deleteResult = sqldb.delete(TableName, where, selectionArgs);
//        LogUtil.d(TAG, "updateAllDataByUserId deleteResult " + deleteResult);
//        for (WorkItem workItem : dataList) {
//            ContentValues cv = new ContentValues();
//            cv = buildContentValues(workItem);
//            cv.put(Remark1, userId);
//            long result = sqldb.insert(TableName, null, cv);
//            LogUtil.d(TAG, "updateAllDataByUserId 插入" + workItem.object_id + "  结果  " + result);
//        }
//    }

    /**
     * 方法描述 : 插入更新待办数据
     *

     */
    public void insertOrUpdate(WorkItem item, String user_id) {
        //根据objid workId workType 更新
        openDB();
        ContentValues cv = new ContentValues();
        String selection = ScheduleId + "=? and " + Remark1 + " = ?";
        String[] selectionArgs = new String[]{item.schedule_id, user_id};
        Cursor cur = sqldb.query(TableName, null, selection, selectionArgs, null, null, null);
        LogUtil.d(TAG, "查找出符合条件的代办事项为" + cur.getCount() + "条");
        if (cur != null && cur.getCount() > 0) {
            LogUtil.d(TAG, "更新" + item.object_id);
            cv = buildContentValues(item);
            sqldb.update(TableName, cv, selection, selectionArgs);
        } else {
            cv = buildContentValues(item);
            cv.put(Remark1, user_id);
            long result = sqldb.insert(TableName, null, cv);
            LogUtil.d(TAG, "插入" + item.object_id + "  结果  " + result);
        }
//        if (TextUtils.isEmpty(content)) return;
//        String insertTimeStr = df.format(new Date(insertTime));
//        openDB();
//        ContentValues cv = new ContentValues();
//        String[] columns = {this.type, this.userid, this.objid, this.isselect, this.content};
//        String selection = this.type + "=? and " + this.userid + "=? and " + this.objid + "=? and " + this.formid + "=?";
//        String[] selectionArgs = new String[]{type, userid, objid, formid};
//        Cursor cur = sqldb.query(TableName, columns, selection, selectionArgs, null, null, null);
//        if (cur != null && cur.getCount() > 0) {
//            cv.put(this.isselect, isselect);
//            sqldb.update(TableName, cv, selection, selectionArgs);
//            LogUtil.v(tag, "insertOrUpdate update>>>" + objid + " isselect:" + isselect);
//        } else {
//            cv.put(this.type, type);
//            cv.put(this.userid, userid);
//            cv.put(this.objid, objid);
//            cv.put(this.isselect, isselect);
//            cv.put(this.content, content);
//            cv.put(this.InsertTime, insertTimeStr);
//            cv.put(this.formid, formid);
//            long result = sqldb.insert(TableName, null, cv);
//            LogUtil.v(tag, "insertOrUpdate insert>>>InsertTime:" + insertTimeStr + " "
//                    + "type:" + type + " userid:" + userid + " objid:" + objid + "isselect:" + isselect + "content:" + content
//                    + "insert result:" + result);
//        }
//        cur.close();
    }

    /**
     * @param scheduleId
     * @param userId
     * @return
     */
    public WorkItem getWorkItemById(String scheduleId, String userId) {
        WorkItem workItem = new WorkItem();
        openDB();
        String selection = ScheduleId + "= ? ";
        String[] selectionArgs = new String[]{scheduleId};
        String[] columns = {FormHasapply, ObjectId, ObjectName, ObjectType, ScheduleId, ServiceobjId, ServiceType, WorkId,
                WorkTypename, WorkType, WorkTime, WorkCycle, WorkTimes, WorkEndtime, WorkFinishtimes, tableName, HandlerId, HandlerKey, HandlerUrlview};
        Cursor cur = sqldb.query(TableName, columns, selection, selectionArgs, null, null, null);
        if (cur != null && cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String formHasApply = cur.getString(0);
                String objid = cur.getString(1);
                String objname = cur.getString(2);
                String objtype = cur.getString(3);
                String schId = cur.getString(4);
                String serviceObjId = cur.getString(5);
                String serviceType = cur.getString(6);
                String workId = cur.getString(7);
                String workTypeName = cur.getString(8);
                String workType = cur.getString(9);
                String workTime = cur.getString(10);
                String workCycle = cur.getString(11);
                String workTimes = cur.getString(12);
                String workEndTime = cur.getString(13);
                String workFinishTime = cur.getString(14);
                String table_name = cur.getString(15);
                String handlerId = cur.getString(16);
                String handlerKey = cur.getString(17);
                String handlerView = cur.getString(18);
                LogUtil.v(TAG, "queryAllData >>> workId:" + workId + " >>userid:" + userId);
                workItem.form_hasapply = formHasApply;
                workItem.object_id = objid;
                workItem.object_name = objname;
                workItem.object_type = objtype;
                workItem.schedule_id = schId;
                workItem.serviceobj_id = serviceObjId;
                workItem.service_type = serviceType;
                workItem.work_id = workId;
                workItem.work_typename = workTypeName;
                workItem.work_type = workType;
                workItem.work_times = workTime;
                workItem.work_cycle = workCycle;
                workItem.work_times = workTimes;
                workItem.work_endtime = workEndTime;
                workItem.work_finishtimes = workFinishTime;
                workItem.table_name = table_name;
                workItem.apply_form_id = handlerId;
                workItem.apply_form_key = handlerKey;
                workItem.apply_form_url = handlerView;
            }
        }
        cur.close();
        LogUtil.v(TAG, "queryWorkItem :" + scheduleId + " userid:" + userId + " table_name" + tableName);
        return workItem;
    }

    /**
     * 方法描述 : 查询所有数据
     *
     * @param userid
     * @return
     */
    public List<WorkItem> queryAllData(String userid) {
        List<WorkItem> list = new ArrayList<WorkItem>();
        openDB();
        String selection = Remark1 + "=?";
        String[] selectionArgs = new String[]{userid};
        String[] columns = {FormHasapply, ObjectId, ObjectName, ObjectType, ScheduleId, ServiceobjId, ServiceType, WorkId, WorkTypename,
                WorkType, WorkTime, WorkCycle, WorkTimes, WorkEndtime, WorkFinishtimes, tableName, HandlerId, HandlerKey, HandlerUrlview};
        String groupBy = WorkType;
        String orderBy = WorkType;
        Cursor cur = sqldb.query(TableName, columns, selection, selectionArgs, null, null, orderBy);
        if (cur != null && cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String formHasApply = cur.getString(0);
                String objid = cur.getString(1);
                String objname = cur.getString(2);
                String objtype = cur.getString(3);
                String schId = cur.getString(4);
                String serviceObjId = cur.getString(5);
                String serviceType = cur.getString(6);
                String workId = cur.getString(7);
                String workTypeName = cur.getString(8);
                String workType = cur.getString(9);
                String workTime = cur.getString(10);
                String workCycle = cur.getString(11);
                String workTimes = cur.getString(12);
                String workEndTime = cur.getString(13);
                String workFinishTime = cur.getString(14);
                String tableName = cur.getString(15);
                String handlerId = cur.getString(16);
                String handlerKey = cur.getString(17);
                String handlerView = cur.getString(18);
                LogUtil.v(TAG, "queryAllData >>> Objectid:" + objid + " >>userid:" + userid + "schId :" + schId);
                WorkItem workItem = new WorkItem();
                workItem.form_hasapply = formHasApply;
                workItem.object_id = objid;
                workItem.object_name = objname;
                workItem.object_type = objtype;
                workItem.schedule_id = schId;
                workItem.serviceobj_id = serviceObjId;
                workItem.service_type = serviceType;
                workItem.work_id = workId;
                workItem.work_typename = workTypeName;
                workItem.work_type = workType;
                workItem.work_times = workTime;
                workItem.work_cycle = workCycle;
                workItem.work_times = workTimes;
                workItem.work_endtime = workEndTime;
                workItem.work_finishtimes = workFinishTime;
                workItem.table_name = tableName;
                workItem.apply_form_id = handlerId;
                workItem.apply_form_key = handlerKey;
                workItem.apply_form_url = handlerView;
                list.add(workItem);
            }
        }
        cur.close();
        LogUtil.v(TAG, "queryAllData count:" + list.size() + " userid:" + userid);
        return list;
    }

    public void DeleteData(String userid) {
        openDB();
        //String[] whereArgs=new String[]{userid};
        int result = sqldb.delete(TableName, null, null);
        LogUtil.v(TAG, "DeleteOneData userid:" + userid + " result:" + result);
    }
}
